package org.example.service;

import org.example.config.MybatisPlusConfig;
import org.example.mapper.ColumnInfoMapper;
import org.example.mapper.ColumnRelationMapper;
import org.example.mapper.TableInfoMapper;
import org.example.model.entity.ColumnInfo;
import org.example.model.entity.ColumnRelation;
import org.example.model.entity.TableInfo;
import org.example.utils.MybatisUtil;

import java.util.List;

/**
 * @author wuyong
 * @date 2025/6/12
 */
public class DbService {
    private final TableInfoMapper tableInfoMapper;
    private final ColumnInfoMapper columnInfoMapper;
    private final ColumnRelationMapper columnRelationMapper;
    public DbService() {
        this.tableInfoMapper = MybatisUtil.getMapper(TableInfoMapper.class);
        this.columnInfoMapper = MybatisUtil.getMapper(ColumnInfoMapper.class);
        this.columnRelationMapper = MybatisUtil.getMapper(ColumnRelationMapper.class);
    }
    public List<ColumnInfo> getColumnByTableName(String tableName){
        return columnInfoMapper.getColumnByTableName(tableName);
    }
    public void saveColumnInfoBatch(List<ColumnInfo> columnInfos) {
        if (columnInfos == null || columnInfos.isEmpty()) return;
        int batchSize = 50;
        for (int i = 0; i < columnInfos.size(); i += batchSize) {
            int end = Math.min(i + batchSize, columnInfos.size());
            List<ColumnInfo> subList = columnInfos.subList(i, end);
            columnInfoMapper.insertBatch(subList);
        }
    }
    public void saveTableBatch(List<TableInfo> tables) {
        if (tables == null || tables.isEmpty()) return;
        int batchSize = 50;
        for (int i = 0; i < tables.size(); i += batchSize) {
            int end = Math.min(i + batchSize, tables.size());
            List<TableInfo> subList = tables.subList(i, end);
            tableInfoMapper.insertBatch(subList);
        }
    }
    public List<TableInfo> getTableInfoByModuleName(String moduleName) {
        return tableInfoMapper.getTableInfoByModuleName(moduleName);
    }
    public List<TableInfo> getTableInfoByModuleNames(List<String> moduleNames) {
        return tableInfoMapper.getTableInfoByModuleNames(moduleNames);
    }
    public List<TableInfo> fillColumnInfo(List<TableInfo> tableInfos) {
        if (tableInfos == null || tableInfos.isEmpty()) return tableInfos;
        for (TableInfo tableInfo : tableInfos) {
            List<ColumnInfo> columnInfos = getColumnByTableName(tableInfo.getTableName());
            tableInfo.setColumnInfos(columnInfos);
        }
        return tableInfos;
    }
    public List<ColumnRelation> getColumnRelation() {
        return columnRelationMapper.getAllColumnRelation();
    }
    public List<ColumnRelation> getColumnRelationByTables(List<String> tableNames) {
        return columnRelationMapper.getColumnRelationByTables(tableNames);
    }
}
